<template>
  <view class="datetime-picker-container" v-if="visible">
    <view class="popup-mask" @tap="cancel"></view>
    <view class="popup-content">
      <view class="datetime-header">
        <view class="popup-left" @tap="cancel">
          <text>取消</text>
        </view>
        <view class="popup-title">{{ title }}</view>
        <view class="popup-right" @tap="confirm">
          <text class="confirm-btn">确定</text>
        </view>
      </view>
      
      <view class="datetime-display" v-if="showDisplay">
        <template v-if="mode === 'datetime'">
          {{ selectedYear }}-{{ selectedMonth }}-{{ selectedDay }} {{ selectedHour }}:{{ selectedMinute }}:{{ selectedSecond }}
        </template>
        <template v-else-if="mode === 'date'">
          {{ selectedYear }}-{{ selectedMonth }}-{{ selectedDay }}
        </template>
        <template v-else-if="mode === 'time'">
          {{ selectedHour }}:{{ selectedMinute }}:{{ selectedSecond }}
        </template>
      </view>
      
      <view class="picker-container">
        <picker-view class="datetime-picker" :indicator-style="indicatorStyle" :value="dateTimeValue" @change="onDateTimeChange">
          <!-- 日期选择列 -->
          <template v-if="mode === 'datetime' || mode === 'date'">
            <picker-view-column>
              <view class="picker-item" v-for="(year, index) in years" :key="'year-'+index">{{ year }}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(month, index) in months" :key="'month-'+index">{{ month }}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(day, index) in days" :key="'day-'+index">{{ day }}</view>
            </picker-view-column>
          </template>
          
          <!-- 时间选择列 -->
          <template v-if="mode === 'datetime' || mode === 'time'">
            <picker-view-column>
              <view class="picker-item" v-for="(hour, index) in hours" :key="'hour-'+index">{{ hour }}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(minute, index) in minutes" :key="'minute-'+index">{{ minute }}</view>
            </picker-view-column>
            <picker-view-column>
              <view class="picker-item" v-for="(second, index) in seconds" :key="'second-'+index">{{ second }}</view>
            </picker-view-column>
          </template>
        </picker-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue';

// 定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择日期和时间'
  },
  initialDate: {
    type: [Date, String],
    default: () => new Date()
  },
  indicatorStyle: {
    type: String,
    default: 'height: 80rpx;'
  },
  mode: {
    type: String,
    default: 'datetime', // 可选值：datetime, date, time
    validator: (value) => ['datetime', 'date', 'time'].includes(value)
  },
  showDisplay: {
    type: Boolean,
    default: true
  }
});

// 定义组件事件
const emit = defineEmits(['update:visible', 'confirm', 'cancel']);

// 日期时间选择器数据
const years = ref([]);
const months = ref([]);
const days = ref([]);
const hours = ref([]);
const minutes = ref([]);
const seconds = ref([]);
const dateTimeValue = ref([]);

// 选中的日期时间值
const selectedYear = ref('');
const selectedMonth = ref('');
const selectedDay = ref('');
const selectedHour = ref('');
const selectedMinute = ref('');
const selectedSecond = ref('');

// 初始化日期时间选择器数据
const initDateTimePicker = () => {
  // 生成年份数据：当前年份前后10年
  const currentYear = new Date().getFullYear();
  years.value = Array.from({length: 20}, (_, i) => String(currentYear - 5 + i));
  
  // 生成月份数据
  months.value = Array.from({length: 12}, (_, i) => String(i + 1).padStart(2, '0'));
  
  // 生成天数数据（默认31天，选择月份时会更新）
  updateDays(31);
  
  // 生成小时数据
  hours.value = Array.from({length: 24}, (_, i) => String(i).padStart(2, '0'));
  
  // 生成分钟数据
  minutes.value = Array.from({length: 60}, (_, i) => String(i).padStart(2, '0'));
  
  // 生成秒钟数据
  seconds.value = Array.from({length: 60}, (_, i) => String(i).padStart(2, '0'));
  
  // 根据模式初始化选择器值
  initDateTimeValue();
};

// 初始化日期时间值
const initDateTimeValue = () => {
  if (props.mode === 'datetime') {
    dateTimeValue.value = [0, 0, 0, 0, 0, 0];
  } else if (props.mode === 'date') {
    dateTimeValue.value = [0, 0, 0];
  } else if (props.mode === 'time') {
    dateTimeValue.value = [0, 0, 0];
  }
};

// 更新天数
const updateDays = (daysInMonth) => {
  days.value = Array.from({length: daysInMonth}, (_, i) => String(i + 1).padStart(2, '0'));
};

// 获取某月的天数
const getDaysInMonth = (year, month) => {
  return new Date(year, month, 0).getDate();
};

// 日期时间选择器变化事件
const onDateTimeChange = (e) => {
  const values = e.detail.value;
  dateTimeValue.value = values;
  
  if (props.mode === 'datetime' || props.mode === 'date') {
    // 更新选中的日期值
    selectedYear.value = years.value[values[0]];
    selectedMonth.value = months.value[values[1]];
    
    // 检查月份天数是否需要更新
    const daysInMonth = getDaysInMonth(Number(selectedYear.value), Number(selectedMonth.value));
    if (days.value.length !== daysInMonth) {
      updateDays(daysInMonth);
      // 如果当前选中的日期超出了新月份的天数，则调整为最后一天
      if (values[2] >= daysInMonth) {
        dateTimeValue.value[2] = daysInMonth - 1;
      }
    }
    
    selectedDay.value = days.value[values[2]] || days.value[0];
  }
  
  if (props.mode === 'datetime' || props.mode === 'time') {
    // 更新选中的时间值
    const timeStartIndex = props.mode === 'datetime' ? 3 : 0;
    selectedHour.value = hours.value[values[timeStartIndex]];
    selectedMinute.value = minutes.value[values[timeStartIndex + 1]];
    selectedSecond.value = seconds.value[values[timeStartIndex + 2]];
  }
};

// 设置初始日期时间
const setInitialDateTime = () => {
  const currentDate = props.initialDate instanceof Date 
    ? props.initialDate 
    : new Date(props.initialDate);
  
  if (props.mode === 'datetime' || props.mode === 'date') {
    const yearIndex = years.value.findIndex(y => y === String(currentDate.getFullYear()));
    const monthIndex = months.value.findIndex(m => m === String(currentDate.getMonth() + 1).padStart(2, '0'));
    const dayIndex = days.value.findIndex(d => d === String(currentDate.getDate()).padStart(2, '0'));
    
    if (props.mode === 'datetime') {
      const hourIndex = hours.value.findIndex(h => h === String(currentDate.getHours()).padStart(2, '0'));
      const minuteIndex = minutes.value.findIndex(m => m === String(currentDate.getMinutes()).padStart(2, '0'));
      const secondIndex = seconds.value.findIndex(s => s === String(currentDate.getSeconds()).padStart(2, '0'));
      
      dateTimeValue.value = [
        yearIndex > -1 ? yearIndex : 0,
        monthIndex > -1 ? monthIndex : 0,
        dayIndex > -1 ? dayIndex : 0,
        hourIndex > -1 ? hourIndex : 0,
        minuteIndex > -1 ? minuteIndex : 0,
        secondIndex > -1 ? secondIndex : 0
      ];
    } else {
      dateTimeValue.value = [
        yearIndex > -1 ? yearIndex : 0,
        monthIndex > -1 ? monthIndex : 0,
        dayIndex > -1 ? dayIndex : 0
      ];
    }
  } else if (props.mode === 'time') {
    const hourIndex = hours.value.findIndex(h => h === String(currentDate.getHours()).padStart(2, '0'));
    const minuteIndex = minutes.value.findIndex(m => m === String(currentDate.getMinutes()).padStart(2, '0'));
    const secondIndex = seconds.value.findIndex(s => s === String(currentDate.getSeconds()).padStart(2, '0'));
    
    dateTimeValue.value = [
      hourIndex > -1 ? hourIndex : 0,
      minuteIndex > -1 ? minuteIndex : 0,
      secondIndex > -1 ? secondIndex : 0
    ];
  }
  
  // 触发一次变化事件，更新选中的值
  onDateTimeChange({
    detail: { value: dateTimeValue.value }
  });
};

// 确认选择
const confirm = () => {
  let result = {};
  
  if (props.mode === 'datetime') {
    const selectedDate = new Date(
      Number(selectedYear.value),
      Number(selectedMonth.value) - 1,
      Number(selectedDay.value),
      Number(selectedHour.value),
      Number(selectedMinute.value),
      Number(selectedSecond.value)
    );
    
    result = {
      date: `${selectedYear.value}-${selectedMonth.value}-${selectedDay.value}`,
      time: `${selectedHour.value}:${selectedMinute.value}:${selectedSecond.value}`,
      dateTime: selectedDate
    };
  } else if (props.mode === 'date') {
    result = {
      date: `${selectedYear.value}-${selectedMonth.value}-${selectedDay.value}`
    };
  } else if (props.mode === 'time') {
    result = {
      time: `${selectedHour.value}:${selectedMinute.value}:${selectedSecond.value}`
    };
  }
  
  emit('confirm', result);
  emit('update:visible', false);
};

// 取消选择
const cancel = () => {
  emit('cancel');
  emit('update:visible', false);
};

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (years.value.length === 0) {
      initDateTimePicker();
    }
    setInitialDateTime();
  }
});

// 组件挂载时初始化
onMounted(() => {
  if (props.visible) {
    initDateTimePicker();
    setInitialDateTime();
  }
});
</script>

<style lang="scss" scoped>
.datetime-picker-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.popup-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
}

.datetime-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-left {
  color: #333;
  font-size: 28rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.popup-right {
  text-align: right;
}

.confirm-btn {
  color: #007AFF;
  font-size: 28rpx;
}

.datetime-display {
  text-align: center;
  padding: 20rpx;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.picker-container {
  height: 500rpx;
  overflow: hidden;
}

.datetime-picker {
  width: 100%;
  height: 100%;
}

.picker-item {
  line-height: 80rpx;
  text-align: center;
  font-size: 32rpx;
}
</style>